package org.yxj.lib_storage;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.format.DateUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 保存图片到相册
 *
 * @author yxj on 2023/10/30
 */
public class SavePictureUtil {

    private Context context;

    public SavePictureUtil(Context context) {
        this.context = context;
    }

    /**
     * 安卓保存相册
     *
     * @param bitmap
     */
    public void androidSaveBitmap(final Bitmap bitmap, final CallBack<SaveImageBean> callBack) {
        if (context != null) {
            new Handler(context.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    if (SDCardUtil.isAfter29() && context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.Q) {
//                        android10SaveImage( bitmap, callBack);
                        saveImageToGalleryQ(context, bitmap, callBack);
                    } else {
                        android10BelowSaveBitmap(bitmap, callBack);
                    }
                }
            });
        }
    }

    /**
     * 安卓10以下保存相册
     *
     * @param b
     * @return
     */
    private void android10BelowSaveBitmap(final Bitmap b, CallBack<SaveImageBean> callBack) {
        FileOutputStream outputStream = null;
        try {
            File f = new File(StorageFileManager.newInstance().rootPath() + File.separator + "image");
            if (!f.exists()) {
                f.mkdir();
            }

            File file = new File(f.getPath() + File.separator + System.currentTimeMillis() + ".png");
            file.createNewFile();
            outputStream = new FileOutputStream(file.getPath());
            b.compress(Bitmap.CompressFormat.PNG, 100, outputStream);

            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
            values.put(MediaStore.Images.Media.MIME_TYPE, "image_layout/jpeg");
            MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), file.getName(), "");
            Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile( file)));
            if (callBack != null) {
                SaveImageBean saveImageBean = new SaveImageBean();
                saveImageBean.uri = uri;
                saveImageBean.FilePath = file.getAbsolutePath();
                callBack.success(saveImageBean);
            }
            LogUtils.LOG_V("[SaveBitmapsUtil]-> is 保存相册成功 29以下 imgPath=" + file.getAbsolutePath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            if (callBack != null) {
                callBack.error(-1, "android10BelowSaveBitmap = " + e.getMessage());
            }
        } catch (IOException e) {
            e.printStackTrace();
            if (callBack != null) {
                callBack.error(-1, "android10BelowSaveBitmap = " + e.getMessage());
            }
        }
    }


    /**
     * android 10 以上版本
     */
    private static void saveImageToGalleryQ(final Context context, final Bitmap image, final CallBack<SaveImageBean> callBack) {
        final long mImageTime = System.currentTimeMillis();
        final String path = StorageFileManager.newInstance().getImgPath();
        ContentValues values = new ContentValues();
//        values.put(MediaStore.MediaColumns.RELATIVE_PATH, path);
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, path);
        //类型
        values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
        //添加时间
        values.put(MediaStore.MediaColumns.DATE_ADDED, mImageTime / 1000);
        //修改时间
        values.put(MediaStore.MediaColumns.DATE_MODIFIED, mImageTime / 1000);
        values.put(MediaStore.MediaColumns.DATE_EXPIRES, (mImageTime + DateUtils.DAY_IN_MILLIS) / 1000);
        values.put(MediaStore.MediaColumns.IS_PENDING, 1);
        ContentResolver resolver = context.getContentResolver();
        final Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        try {
            OutputStream out = resolver.openOutputStream(uri);
            if (!image.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                if (callBack != null) {
                    callBack.error(-1, "保存失败！");
                }
                return;
            }
            values.clear();
            values.put(MediaStore.MediaColumns.IS_PENDING, 0);
            values.putNull(MediaStore.MediaColumns.DATE_EXPIRES);
            resolver.update(uri, values, null, null);

            new Handler(context.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    if (callBack != null) {
                        SaveImageBean saveImageBean = new SaveImageBean();
                        saveImageBean.uri = uri;
                        saveImageBean.FilePath = path;
                        callBack.success(saveImageBean);
                    }
                }
            });
        } catch (Exception e) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                resolver.delete(uri, null);
            }
            if (callBack != null) {
                callBack.error(-1, e.getMessage());
            }
        }
    }


    /**
     * 保存图片到相册 自动分配uri
     *
     * @param bitmap
     * @return
     */
    private void android10SaveImage(final Bitmap bitmap, final CallBack<SaveImageBean> callBack) {
        LogUtils.LOG_V("[SaveBitmapsUtil]-> android10SaveImage is 保存相册成功 29以上 ");
        new Thread(new Runnable() {
            @Override
            public void run() {
                final Uri saveUri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
                OutputStream outputStream = null;
                try {
                    outputStream = context.getContentResolver().openOutputStream(saveUri);
                    final OutputStream finalOutputStream = outputStream;
                    if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, finalOutputStream)) {
                        //保存成功
                        Intent intent = new Intent();
                        intent.setData(saveUri);
                        context.sendBroadcast(intent);
                        // 最后通知图库更新
                        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, saveUri).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION));
                    }

                    new Handler(context.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            String imgPath = PathConvertUriUtil.PathConvertUri(context, saveUri);
                            if (callBack != null) {
                                SaveImageBean saveImageBean = new SaveImageBean();
                                saveImageBean.uri = saveUri;
                                saveImageBean.FilePath = imgPath;
                                callBack.success(saveImageBean);
                            }
                            LogUtils.LOG_V("[SaveBitmapsUtil]-> is 保存相册成功 29以上 imgPath=" + imgPath);
                        }
                    });
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    if (callBack != null) {
                        callBack.error(-1, "android10SaveImage = " + e.getMessage());
                    }
                }
            }
        }).start();
    }
}
